package com.example.its2021606134chh.ETCModule;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.its2021606134chh.R;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ETC_recharge_recordFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ETC_recharge_recordFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Spinner spRecTimeArr;
    private Button btnRecSearch;
    private RecyclerView rvETCRecharge;
    MySQLiteOpenHelper openHelper;
    SQLiteDatabase database;
    private List<Cars> list = new ArrayList<>();

    public ETC_recharge_recordFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ETC_recharge_recordFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ETC_recharge_recordFragment newInstance(String param1, String param2) {
        ETC_recharge_recordFragment fragment = new ETC_recharge_recordFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_e_t_c_recharge_record, container, false);
        // Inflate the layout for this fragment
        spRecTimeArr = (Spinner) view.findViewById(R.id.spRecTimeArr);
        btnRecSearch = (Button) view.findViewById(R.id.btnRecSearch);
        rvETCRecharge = (RecyclerView) view.findViewById(R.id.rvETCRecharge);
        rvETCRecharge.setLayoutManager(new LinearLayoutManager(getContext()));

//        Date minDate = stringToDate("1970-01-01 00:00:00");
//        Date dNow = new Date();
//        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
//        String sNow = ft.format(dNow);
//        Date maxDate = stringToDate(sNow);

        openHelper = new MySQLiteOpenHelper(getContext(), "ETCaccount1.db", null, 1);
        database = openHelper.getReadableDatabase();
        try (Cursor cursor = database.query("etccar", null, null, null, null, null, null)) {
            if (cursor.moveToFirst()) {
                do {
                    int carID = cursor.getInt(0);
                    int carRecharge = cursor.getInt(2);
                    String user = cursor.getString(3);
                    String time = cursor.getString(4);
                    list.add(new Cars(carID, carRecharge, user, time));
//                Log.i("TAG", carID + " " + carBalance + " " + carRecharge + " " + user + " " + time);
                } while (cursor.moveToNext());
            }

//            默认时间降序
            Collections.sort(list, new Comparator<Cars>() {
                @Override
                public int compare(Cars l1, Cars l2) {
                    Date time1 = ETC_recharge_recordFragment.stringToDate(l1.getTime());
                    Date time2 = ETC_recharge_recordFragment.stringToDate(l2.getTime());
                    long start = time1.getTime();
                    long end = time2.getTime();
                    return Long.compare(end, start);
                }
            });

            rvETCRecharge.setAdapter(new CarsRViewAdapter(list));
        } catch (Exception e) {
            Toast.makeText(getActivity(), "暂无历史记录", Toast.LENGTH_SHORT).show();
        } finally {
            database.close();
        }

        btnRecSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.clear();
                String timeArr = spRecTimeArr.getSelectedItem().toString();
                database = openHelper.getReadableDatabase();
                try (Cursor cursor = database.query("etccar", null, null, null, null, null, null)) {
                    if (cursor.moveToFirst()) {
                        do {
                            int carID = cursor.getInt(0);
                            int carRecharge = cursor.getInt(2);
                            String user = cursor.getString(3);
                            String time = cursor.getString(4);
//                            Date dTime = stringToDate(time);
//                            if (dTime.after(minDate)) { }
                            list.add(new Cars(carID, carRecharge, user, time));
                        } while (cursor.moveToNext());
                    }
//                  根据spinner选择排序
                    if (timeArr.equals("时间降序")) {
                        Collections.sort(list, new Comparator<Cars>() {
                            @Override
                            public int compare(Cars l1, Cars l2) {
                                Date time1 = ETC_recharge_recordFragment.stringToDate(l1.getTime());
                                Date time2 = ETC_recharge_recordFragment.stringToDate(l2.getTime());
                                long start = time1.getTime();
                                long end = time2.getTime();
                                return Long.compare(end, start);
                            }
                        });
                    } else {
                        Collections.sort(list, new Comparator<Cars>() {
                            @Override
                            public int compare(Cars l1, Cars l2) {
                                Date time1 = ETC_recharge_recordFragment.stringToDate(l1.getTime());
                                Date time2 = ETC_recharge_recordFragment.stringToDate(l2.getTime());
                                long start = time1.getTime();
                                long end = time2.getTime();
                                return Long.compare(start, end);
                            }
                        });
                    }
                    rvETCRecharge.setAdapter(new CarsRViewAdapter(list));
                } catch (SQLException ignored) {
                    Toast.makeText(getActivity(), "暂无历史记录", Toast.LENGTH_SHORT).show();
                } finally {
                    database.close();
                }
            }
        });
        return view;
    }
    public static Date stringToDate(String dateString){
        ParsePosition position = new ParsePosition(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.parse(dateString,position); //将字符串转换为Date日期格式
    }
    public static String dateToStrLong(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(dateDate);
        return dateString;
    }
}